using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Drawing;

namespace Map2.Xml
{
    class SaveXml
    {
        private List<Building> buildings;
        private int mapWidth, mapHeight;
        private string file;
        private XmlTextWriter tw;

        public SaveXml(string file, List<Building> buildings, Size mapSize)
        {
            this.buildings = buildings;
            this.file = file;
            mapHeight = mapSize.Height;
            mapWidth = mapSize.Width;
            initDocument();
            beginDocument();
            addBuildings();
            endDocument();
        }

        private void initDocument()
        {
            tw = new XmlTextWriter(file, null);
            tw.WriteStartDocument(true);
        }

        private void beginDocument()
        {
            tw.WriteStartElement("map");
            tw.WriteStartElement("width");
            tw.WriteValue(mapWidth);
            tw.WriteEndElement();
            tw.WriteStartElement("height");
            tw.WriteValue(mapHeight);
            tw.WriteEndElement();
        }

        private void addBuildings()
        {
            foreach (Building b in buildings)
            {
                tw.WriteStartElement("building");
                foreach (Point p in b.getPoints())
                {
                    tw.WriteStartElement("point");

                    tw.WriteStartElement("x");
                    tw.WriteValue(p.X);
                    tw.WriteEndElement();

                    tw.WriteStartElement("y");
                    tw.WriteValue(p.Y);
                    tw.WriteEndElement();

                    tw.WriteEndElement();
                }
                tw.WriteEndElement();
            }
        }

        private void endDocument()
        {
            tw.WriteEndElement();
            tw.Flush();
            tw.Close();
        }
    }
}
